package com.atguigu.srb.core.controller.admin;

import com.atguigu.common.result.R;
import com.atguigu.srb.core.pojo.entity.User;
import com.atguigu.srb.core.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api(tags = "用户登录")
@CrossOrigin
@RestController
@RequestMapping("/admin/core/")
@Slf4j
public class LoginController {

    @Resource
    private UserService userService;
    //用户注册
    @ApiOperation("用户注册")
    @PostMapping("/save")
    public R login (
            @ApiParam(value = "用户对象", required = true)
            @RequestBody User user
            ){

        boolean save = userService.save(user);
        if(save){
            return R.ok().message("注册成功");

        }else {
            return R.error().message("注册失败");
        }

    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public R tologin(
            @ApiParam(value = "用户账号")
            @RequestParam("username") String username,
            @RequestParam("password") String password
    )
    {
        //获取当前用户
       Subject subject= SecurityUtils.getSubject();
       //封装用户的登陆数据
       UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);

       try {
           //执行登录方法
           subject.login(usernamePasswordToken);
           return  R.ok().message("登陆成功");
       }catch (UnknownAccountException e){
           return  R.error().message("用户名不存在");
       }catch (IncorrectCredentialsException e){
           return R.error().message("密码错误");
       }


    }



}
